// pages/server_end/apply_server/apply_server.js
const app = getApp();
const request = require('../../../utils/request.js');
const url = require('../../../utils/url.js');
const cookie = require('../../../utils/cookie.js');

const WxParse = require('../../../wxParse/wxParse.js');

Page({

    /**
     * 页面的初始数据
     */
    data: {
       tagIds: [],
       imgs: [],
       picList: [],
       imgss: [],
       picList: [],
        serverType: "",
        serverTypeRange: [],
        categorylist: [],
        servicetaglist: [],
        taglist: [],
		 sevice_category_id: [],
        show: 0,
        show1: false,
        show2: false,
		show3: false,
		show4: false,
		cagtegoryids:''
    },
    closeTime2() {
        this.setData({
            show2: false
        })
    },
    closeTime1() {
        this.setData({
            show1: false
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        //获取标签信息
		console.log('servertype:'+options.servertype);
		this.setData({
		    cagtegoryids:options.servertype
		})
        this.getServiceTag();
        this.getServiceType();
        var that = this;
    },
 
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
            
      

    },
    // async getAgreement(){
    //     let param = {
    //       scoure: 'wxapp',
    //       token: that.data.token
    //   }
    // },
        // const res = await request.request(url.agreement,param,url.REQUEST_METHOD_GET);
 
//   console.log(res);

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        var that = this;
        cookie.getCookie('userInfo', function (res) {
            if (res) {
                var etime = Date.parse(new Date()) / 1000;

                if (etime < res.expiretime) {
                    that.setData({
                        login: 1,
                        token: res.token
                    })
                }
            }
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    changeAgreement(){
        this.setData({
            agreement:false
        })
    },
 // 删除图片
    deleteImg: function (e) {
        var imgs = this.data.imgs;
        var picList = this.data.picList;
        var index = e.currentTarget.dataset.index;
        imgs.splice(index, 1);
        picList.splice(index, 1);
        this.setData({
            imgs: imgs,
            picList: picList
        });
        console.log(picList);
    },
    chooseImg: function (e) {
        var that = this;
        var imgs = this.data.imgs;
        if (imgs.length >= 3) {
            this.setData({
                lenMore: 1
            });
            setTimeout(function () {
                that.setData({
                    lenMore: 0
                });
            }, 2500);
            return false;
        }
        var count = 3 - imgs.length;
        if (count < 1) {
            return false;
        }

        wx.chooseImage({
            count: count, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                if (res.errMsg == "chooseImage:ok") {
                    wx.showLoading({ //显示loding提示框
                        title: '正在上传中...',
                    })
                    let picList = that.data.picList
                    var imgs = that.data.imgs;
                    res.tempFilePaths.forEach((item, index) => {
                        imgs.push(item)
                        that.setData({
                            imgs: imgs,
                        });
                        wx.uploadFile({
                            url: url.HttpServerHostAddress + url.uploadpic,
                            filePath: item,
                            name: 'file',
                            formData: {
                                token: that.data.token
                            },
                            success: function (res) {
                                let ress = JSON.parse(res.data)
                                if (ress.code == 1) {
                                    var picList = that.data.picList;
                                    picList.push(JSON.parse(res.data).data.url);
                                    that.setData({
                                        picList: picList,
                                    })
                                    console.log(picList);
                                } else {
                                    wx.showToast({
                                        title: JSON.parse(res.data).msg,
                                        icon: 'none',
                                        duration: 3000
                                    })
                                    return;
                                }
                            },
                            fail: res => {
                                console.log(res)
                            }
                        })
                    })
                    wx.hideLoading(); //隐藏loading提示框
                }
            }
        });
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    changecontactname(e) {
        this.setData({
            contact_name: e.detail.value
        })
    },
    changecontacttel(e) {
        this.setData({
            contact_tel: e.detail.value
        })
    },
    changeaddr(e) {
        this.setData({
            addr_detail: e.detail.value
        })
    },
    changedesc(e) {
        this.setData({
            desc: e.detail.value
        })
    },
    getServiceTag() {
        var that = this;
        let param = {
            scoure: 'wxapp',
            token: that.data.token
        }
        wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
        request.request(url.taglist, param, url.REQUEST_METHOD_GET).then((res) => {
            wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
            if (res.data.code == 1) {
                that.setData({
                    servicetaglist: res.data.data
                })
            }
        })
    },
    getServiceType() {
        var that = this;
		var cityName = wx.getStorageSync('cityName');
        let param = {
            scoure: 'wxapp',
            token: that.data.token,
			cityName:cityName
        }
        wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
        request.request(url.secondcategorylist, param, url.REQUEST_METHOD_GET).then((res) => {
            wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
            if (res.data.code == 1) {
                that.setData({
                    serverTypeRange: res.data.data,
                    categorylist: res.data.data
                })
            }
			
			var ids = this.data.cagtegoryids.split(',');
			ids.forEach(function(id) {
			  that.initType(id);
			});
        })
    },
    showtag() {
        this.setData({
            show1: true
        })
    },
	
    closeTime() {
        this.setData({
            show1: false
        })
    },
    open1() {
        this.setData({
            show2: true
        })
    },
    closeTime2() {
        this.setData({
            show1: false,
            show2: false
        })
    },
    choseTag(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        that.data.servicetaglist.forEach((item, index) => {
            console.log(item.id);
            if (item.id == id) {
                if (item.active == 1) {
                    var active = 0;
                } else {
                    var active = 1;
                }
                var sItem = 'servicetaglist[' + index + '].active';
                this.setData({
                    [sItem]: active
                })
            }
        });
        var array = [];
        var arrayIds = [];
        that.data.servicetaglist.forEach((item, index) => {
            if (item.active == 1) {
                array.push(that.data.servicetaglist[index]);
                arrayIds.push(that.data.servicetaglist[index].id);
            }
        })
        that.setData({
            taglist: array,
            tagIds: arrayIds
        })
    },
    choseType(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        that.data.categorylist.forEach((item, index) => {
            if (item.id == id) {
                if (item.active == 1) {
                    var active = 0;
                } else {
                    var active = 1;
                }
                var sItem = 'categorylist[' + index + '].active';
                that.setData({
                    [sItem]: active
                })
            }
        });
        var array = [];
        var arrayIds = [];
        that.data.categorylist.forEach((item, index) => {
            if (item.active == 1) {
                array.push(that.data.categorylist[index].name);
                arrayIds.push(that.data.categorylist[index].id);
            }
        })

        that.setData({
            serverType: array,
            sevice_category_id: arrayIds
        })
    },
	initType(id) {
	    var that = this;
	    that.data.categorylist.forEach((item, index) => {
	        if (item.id == id) {
	            if (item.active == 1) {
	                var active = 0;
	            } else {
	                var active = 1;
	            }
	            var sItem = 'categorylist[' + index + '].active';
	            that.setData({
	                [sItem]: active
	            })
	        }
	    });
	    var array = [];
	    var arrayIds = [];
	    that.data.categorylist.forEach((item, index) => {
	        if (item.active == 1) {
	            array.push(that.data.categorylist[index].name);
	            arrayIds.push(that.data.categorylist[index].id);
	        }
	    })
	
	    that.setData({
	        serverType: array,
	        sevice_category_id: arrayIds
	    })
	},
	applyMsg(){
		 var that = this;
		wx.requestSubscribeMessage({
		  tmplIds: [
			'q9Js-vQrnKFfxtsIYMrYF6CQgNNsPITiZtcznzk8P-M',
		    'WCOeBpOwto_yU4ZM-hUmQePvbfY_lxKyaFK5Yi7nzao',		   
			'SOnJPXow5f0XddOr1jQ-3wdd6V1SifOHJMdQtPbJNo0'
		  ],
		  success: (res) => {
			  console.log(res)
		    that.apply(that);
		  },
		  fail: (res) => {
			    console.log(res)
		    that.apply(that);
		  },
		})
	},
    apply(that) {
        if (that.data.sevice_category_id.length == 0) {
            wx.showToast({
                title: '请选择服务类型',
                icon: 'none'
            })
            return false;
        }

        let param = {
            scoure: 'wxapp',
            token: that.data.token,
            service_category_id: that.data.sevice_category_id,
            images: that.data.picList,

        }
		console.log(param);
        wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
        request.request(url.update_user_apply_image, param, url.REQUEST_METHOD_POST).then((res) => {
            wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
            wx.showToast({
                title: res.data.msg,
                icon: "none"
            });
			
			setTimeout(function () {
			    wx.navigateTo({
			      url: '/pages/server_end/mine_sf/mine_sf'
			    })
			}, 1500);	
            })


        
    }
})